/*
 * @lc app=leetcode.cn id=14 lang=typescript
 *
 * [14] 最长公共前缀
 */

// @lc code=start
function longestCommonPrefix(strs: string[]): string {
  // 将前缀和字符串比较，返回二者最长公共前缀
  const compare = (prefix: string, str: string): string => {
    let res = '';
    const n = prefix.length;
    for (let i = 0; i < n; i++) {
      if (i === str.length || prefix[i] !== str[i]) return res;
      res += prefix[i];
    }

    return res;
  };

  // 初始化第一个串为最长公共前缀
  let ans = strs[0];
  const n = strs.length;
  for (let i = 1; i < n; i++) {
    // 每次比较返回公共前缀
    ans = compare(ans, strs[i]);
  }

  return ans;
}
// @lc code=end
